package interfaces.batch.legacy.importlegacy.jenkins.service.extractor.jenkins;

import domain.model.project.Project;
import domain.model.project.ProjectDeveloper;
import domain.model.project.ProjectStatus;
import domain.model.project.support.ProjectBuilder;
import domain.model.project.support.projectdeveloper.ProjectDeveloperBuilder;
import domain.model.project.support.projectscm.ProjectSCMBuilder;
import interfaces.batch.legacy.importlegacy.jenkins.domain.OutputCSVJobObj;
import interfaces.batch.legacy.importlegacy.jenkins.domain.jenkins.job.ConfigJob;
import interfaces.batch.legacy.importlegacy.jenkins.service.extractor.maven.pom.POMContentExtractor;
import org.apache.maven.model.Developer;
import org.apache.maven.model.Model;
import org.apache.maven.model.Scm;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.integration.Message;
import org.springframework.integration.annotation.ServiceActivator;
import plugins.buildjava.projecttype.JavaBuildProjectTypeBuilder;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Gregory Boissinot
 */
public class OutputObjBuilder {
    public static final String SCM_CONNECTION_TANGO_CS = "${scm.connection.svn.tango-cs}:";
    public static final String SCM_CONNECTION_TANGO_DS = "${scm.connection.svn.tango-ds}";
    public static final String SCM_CONNECTION_CVS = "${scm.connection.cvs.soleil}";

    private POMContentExtractor pomContentExtractor;

    @Required
    public void setPomContentExtractor(POMContentExtractor pomContentExtractor) {
        this.pomContentExtractor = pomContentExtractor;
    }


    @ServiceActivator
    @SuppressWarnings("unused")
    public Project buildObj(Message<ConfigJob> messageConfigJob) {

        ConfigJob configJob = messageConfigJob.getPayload();

        OutputCSVJobObj.Builder builder = new OutputCSVJobObj.Builder();
        String jobName = configJob.getName();
        builder.name(jobName);
        builder.desc(configJob.getDesc());
        builder.disabled(configJob.isDisabled());
        builder.functionalJobLanguage(configJob.getFunctionalJobLanguage());
        builder.functionalJobType(configJob.getFunctionalJobType());
        builder.trigger(configJob.getTrigger());
        builder.buildSteps(configJob.getBuildSteps());
        builder.cvsRoot(configJob.getCvsRoot());
        builder.cvsModule(configJob.getCvsModule());
        builder.cvsBranche(configJob.getCvsBranche());
        builder.svnURL(configJob.getSvnURL());
        builder.gitURL(configJob.getGitURL());
        builder.platforms(configJob.getPlatforms());

        final Map module_map = (Map) messageConfigJob.getHeaders().get("MODULE_MAP");
        String pomContent = pomContentExtractor.getPomContent(configJob, module_map);
//        if (pomContent != null) {
//            DeveloperInfoRetriever developerInfoRetriever = new DeveloperInfoRetriever();
//            builder.developers(developerInfoRetriever.getDevelopers(pomContent));
//        }

        if (pomContent == null) {
            throw new RuntimeException();
        }
        StringReader stringReader = new StringReader(pomContent);
        Model model = getModel(stringReader);

        String groupId = "";
        if (model.getGroupId() == null) {
            System.out.println("####NULL " + model.getArtifactId());
            groupId = model.getParent().getGroupId();
        } else {
            groupId = model.getGroupId();
        }
        ProjectBuilder projectBuilder = new ProjectBuilder(groupId, model.getArtifactId(), ProjectStatus.OPEN);


        List mavenDevelopers = model.getDevelopers();
        List<ProjectDeveloper> projectDevelopers = new ArrayList<ProjectDeveloper>();
        if (mavenDevelopers != null) {
            for (Object mavenDeveloperObject : mavenDevelopers) {
                Developer mavenProjectDeveloper = (Developer) mavenDeveloperObject;
                ProjectDeveloperBuilder projectDeveloperBuilder = new ProjectDeveloperBuilder(mavenProjectDeveloper.getId());
                projectDeveloperBuilder.name(mavenProjectDeveloper.getName());
                projectDeveloperBuilder.email(mavenProjectDeveloper.getEmail());
                projectDeveloperBuilder.organization(mavenProjectDeveloper.getOrganization());
                projectDeveloperBuilder.organizationUrl(mavenProjectDeveloper.getOrganizationUrl());
                projectDevelopers.add(projectDeveloperBuilder.build());
            }
        } else {
            System.out.println("Maven developers NULL = " + model.getArtifactId());
        }

        if (jobName.endsWith("_JAR")) {
            JavaBuildProjectTypeBuilder javaBuildProjectTypeBuilder = new JavaBuildProjectTypeBuilder();
            javaBuildProjectTypeBuilder.projectDeveloperList(projectDevelopers);
            javaBuildProjectTypeBuilder.sourceCompatibility("1.6");
            javaBuildProjectTypeBuilder.targetCompatibility("1.6");
            projectBuilder.projectType(javaBuildProjectTypeBuilder.build());
        }

        Scm scm = model.getScm();

        if (scm != null) {
            String urlSCM = scm.getConnection();
            if (urlSCM.startsWith(SCM_CONNECTION_TANGO_CS)) {
                urlSCM = urlSCM.replace(SCM_CONNECTION_TANGO_CS, "scm:svn:http://svn.code.sf.net/p/tango-cs/code/");
            } else if (urlSCM.startsWith(SCM_CONNECTION_TANGO_DS)) {
                urlSCM = urlSCM.replace(SCM_CONNECTION_TANGO_DS, "scm:svn:http://svn.code.sf.net/p/tango-ds/code");
            } else if (urlSCM.startsWith(SCM_CONNECTION_CVS)) {
                urlSCM = urlSCM.replace(SCM_CONNECTION_CVS, "scm:cvs:pserver:anonymous:@ganymede.synchrotron-soleil.fr:/usr/local/CVS");
            } else if (urlSCM.contains("scm:svn:https://svn.code.sf.net")) {
                urlSCM = urlSCM.replace("scm:svn:https://svn.code.sf.net", "scm:svn:http://svn.code.sf.net");
            }

            System.out.println("URL " + urlSCM);
            projectBuilder.projectSCM(new ProjectSCMBuilder(urlSCM).build());
        } else {
            System.out.println("SCM URL NULL = " + model.getArtifactId());
        }

        return projectBuilder.build();
    }

    public Model getModel(Reader pomReader) {
        if (pomReader == null) {
            throw new NullPointerException("A pom content as reader object is required.");
        }
        try {
            final MavenXpp3Reader mavenXpp3Reader = new MavenXpp3Reader();
            return mavenXpp3Reader.read(pomReader);
        } catch (XmlPullParserException xe) {
            //TODO check business exception
            throw new RuntimeException("Can't read Maven Model", xe);
        } catch (IOException ioe) {
            //TODO check business exception
            throw new RuntimeException("Can't read Maven Model", ioe);
        }
    }


}
